package alarm

import (
	"encoding/json"
	"fmt"
	logic2 "iot-base/auth/api/logic"
	"iot-base/auth/common/socket"
	"iot-base/auth/config"
	"iot-base/auth/db"
	"iot-base/auth/logger"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
	"iot-base/auth/utils"
	"iot-base/common/eventtype"
	"iot-base/common/notify"
	"strconv"
	"time"
)

type Alarm struct {
}

func NewAlarm() *Alarm {
	return &Alarm{}
}

func (a *Alarm) Run() {
	notify.SubAlarm(func(param *eventtype.Alarm) {
		logger.Log.Infof("alarm msg:=%v", param)
		// 告警信息.
		a.SendAlarm(*param)
		// 触发订阅告警
		utils.AntsPool.Submit(func() {
			key := fmt.Sprintf("%s#%v", db.KeySubStationAlarm, param.StationID)
			var incr int64
			if param.Flag == "END" {
				incr = -1
			} else {
				incr = 1
			}
			db.NewRedis().HIncrBy(key, param.CatalogID, incr)
			//推送订阅告警
			a.SendSubscribeAlarm(*param)
		})
	})
}

// SendAlarm 发送告警.
func (a *Alarm) SendAlarm(param eventtype.Alarm) {
	//{"flag":"END","t_id":"ipc251","mindex":0,"alarm_id":"2","station_id":"4220b3e6-44e7-4fe9-91a0-89f6d2727858","station_name":"科迪隆办公室","time":1624519802,"catalog_id":"COMMON","properties":null,"params":null,"clear_time":1624519802,"thing_name":"ipc251","alarm_name":"下线","m_name":"","sub_name":"","level":3}
	_, _ = json.Marshal(param)
	var ClearTime string
	if param.ClearTime != 0 {
		ClearTime = time.Unix(param.ClearTime, 0).Format("2006/01/02 15:04:05")
	}
	req := types2.RespAlarm{
		StationId:   param.StationID,
		StationName: param.StationName,
		Flag:        param.Flag,
		ThingId:     param.TID,
		ThingName:   param.ThingName,
		CatalogId:   param.CatalogID,
		Level:       param.Level,
		Mindex:      param.Mindex,
		AlarmId:     param.AlarmID,
		AlarmName:   param.AlarmName,
		ClearTime:   ClearTime,
		MName:       param.MName,
		SubName:     param.SubName,
		Time:        time.Unix(param.Time, 0).Format("2006/01/02 15:04:05"),
	}
	thingInfo, err := svc.Dao.TThings.GetThingById(param.StationID)
	if err == nil {
		req.ModelId = thingInfo.ModelID
	}
	logic2.NewAlarmLogic().SendGroupAlarm(req)
}

// SendSubscribeAlarm 发送订阅告警
func (a *Alarm) SendSubscribeAlarm(param eventtype.Alarm) {
	ids := socket.Sub.GetSubUserIds(param.StationID)
	if len(ids) == 0 {
		return
	}
	key := fmt.Sprintf("%s#%v", db.KeySubStationAlarm, param.StationID)
	resp := types2.NewSocketIoResult()
	result, err := db.NewRedis().HGetAll(key)
	if err != nil {
		return
	}
	msgData := make(map[string]interface{})
	for k, v := range result {
		value, _ := strconv.Atoi(v)
		msgData[k] = value
	}
	for _, id := range ids {
		sendMsg := make(map[int64]socket.SocketMsg)
		sendMsg[id] = socket.SocketMsg{
			Event: config.EventSubscribeAlarm,
			Msg:   resp.Success(msgData, ""),
		}
		socket.Manager.UidBroadcast <- sendMsg
	}

}
